﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using OpenNETCF.Drawing.Imaging;

namespace HandRise.MBHOP.Controls
{
    public partial class ImageDataList : Control
    {
        public ImageDataList()
        {

        }
        #region 属性


        private Object dataSource = null;
        /// <summary>
        /// 数据源

        /// </summary>
        public Object DataSource
        {
            get
            {
                return dataSource;
            }
            set
            {
                dataSource = value;
                //DataBind();
            }
        }

        string displayMember = "";
        /// <summary>
        /// 要显示的属性

        /// </summary>
        public string DisplayMember
        {
            get
            {
                return displayMember;
            }
            set
            {
                displayMember = value;
            }
        }


        string imageMember = "";
        /// <summary>
        /// 要显示的图形

        /// </summary>
        public string ImageMember
        {
            get
            {
                return imageMember;
            }
            set
            {
                imageMember = value;
            }
        }
        string keyMember = "";
        /// <summary>
        /// 主键
        /// </summary>
        public string KeyMember
        {
            get
            {
                return keyMember;
            }
            set
            {
                keyMember = value;
            }
        }

        bool isRadio = true;
        /// <summary>

        Color itemBackColor = Color.White;
        /// <summary>
        /// 弹起时的按钮背景色

        /// </summary>
        public Color ItemBackColor
        {
            set
            {
                itemBackColor = value;
            }
            get
            {
                return itemBackColor;
            }
        }

        Color selectItemBackColor = Color.LightBlue;
        /// <summary>
        /// 按下时的按钮背景色

        /// </summary>
        public Color SelectItemBackColor
        {
            set
            {
                selectItemBackColor = value;
            }
            get
            {
                return selectItemBackColor;
            }
        }

        /// <summary>
        /// 文本的字体

        /// </summary>
        public override Font Font
        {
            get
            {
                return new Font("雅黑", ItemFontSize, FontStyle.Regular);
            }
        }

        /// <summary>
        /// 文本的字体

        /// </summary>
        private Font ItemFont
        {
            get
            {
                if (ItemFontSize <= 0)
                    return new Font("雅黑", 1, FontStyle.Regular);
                else
                    return new Font("雅黑", ItemFontSize, FontStyle.Regular);
            }
        }

        /// <summary>
        /// 按下时文本的字体
        /// </summary>
        private Font SelectItemFont
        {
            get
            {
                if (SelectItemFontSize <= 0)
                    return new Font("雅黑", 1, FontStyle.Regular);
                else
                    return new Font("雅黑", SelectItemFontSize, FontStyle.Regular);
            }
        }

        int itemFontSize = 12;
        /// <summary>
        /// 弹起时的文本字号
        /// </summary>
        [DefaultValue(12)]
        public int ItemFontSize
        {
            set
            {
                itemFontSize = value;
            }
            get
            {
                return itemFontSize;
            }
        }

        int selectItemFontSize = 12;
        /// <summary>
        /// 按下时的文本字号
        /// </summary>
        [DefaultValue(12)]
        public int SelectItemFontSize
        {
            set
            {
                selectItemFontSize = value;
            }
            get
            {
                return selectItemFontSize;
            }
        }

        Color itemForeColor = Color.Black;
        /// <summary>
        /// 弹起时的文本颜色
        /// </summary>

        public Color ItemForeColor
        {
            set
            {
                itemForeColor = value;
            }
            get
            {
                return itemForeColor;
            }
        }

        Color selectItemForeColor = Color.White;
        /// <summary>
        /// 按下时的文本颜色
        /// </summary>
        public Color SelectItemForeColor
        {
            set
            {
                selectItemForeColor = value;
            }
            get
            {
                return selectItemForeColor;
            }
        }

        int leftSpace = 0;
        /// <summary>
        /// 文本的左边距
        /// </summary>
        public int LeftSpace
        {
            get
            {
                return leftSpace;
            }
            set
            {
                if (value < 0)
                    value = 0;
                leftSpace = value;
            }
        }

        int rightSpace = 0;
        /// <summary>
        /// 文本的右边距
        /// </summary>
        public int RightSpace
        {
            get
            {
                return rightSpace;
            }
            set
            {
                if (value < 0)
                    value = 0;
                rightSpace = value;
            }
        }

        int pageSize = 4;
        /// <summary>
        /// 每页的数量

        /// </summary>
        [DefaultValue(4)]
        public int PageSize
        {
            get
            {
                return pageSize;
            }
            set
            {
                if (value < 0)
                    value = 0;
                pageSize = value;
            }
        }

        int pageCount = 0;
        /// <summary>
        /// 总页数

        /// </summary>
        public int PageCount
        {
            get
            {
                return pageCount;
            }
        }

        internal int pageIndex = 0;
        /// <summary>
        /// 当前页索引

        /// </summary>
        public int PageIndex
        {
            get
            {
                return pageIndex;
            }
        }

        int itemMargin = 4;
        /// <summary>
        /// 项的间距
        /// </summary>
        [DefaultValue(4)]
        public int ItemMargin
        {
            get
            {
                return itemMargin;
            }
            set
            {
                if (value < 0)
                    value = 0;
                itemMargin = value;
            }
        }

        int labelHigh = 0;
        /// <summary>
        /// 图标框长度

        /// </summary>
        public int LabelHigh
        {
            get
            {
                return labelHigh;
            }
            set
            {
                if (value < 0)
                    value = 0;
                labelHigh = value;
            }
        }

        //按下的对象的标识列表
        private List<string> selectItemKey = new List<string>();
        /// <summary>
        /// 选中的项的标识列表

        /// </summary>
        public List<string> SelectItemKey
        {
            get
            {
                return selectItemKey;
            }
        }

        //按下的对象的索引列表
        private List<int> selectIndex = new List<int>();
        /// <summary>
        /// 选中的项的索引

        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public List<int> SelectIndex
        {
            get
            {
                return selectIndex;
            }
        }

     
        internal bool textCenter = false;
        /// <summary>
        /// 文本是否居中
        /// </summary>
        internal bool TextCenter
        {
            get
            {
                return textCenter;
            }
            set
            {
                textCenter = value;
            }
        }


        //总数据项数

        int dataCount = 0;

        //文本显示属性

        PropertyInfo proTextMember = null;
        //主键属性
        PropertyInfo proImageMember = null;
        //图形属性
        PropertyInfo proValueMember = null;
        //数据源的项列表属性

        PropertyInfo proItemMember = null;
        //当前的聚焦索引,初始为第一个控件

        internal int currIndex = 0;

        //当前页的范围
        int rangeMin = 0;
        int rangeMax = 0;

            public int exeTime = 0;

        #endregion

        /// <summary>
        /// 项单击事件

        /// </summary>
        public event EventImageItemClick OnItemClick;

        /// <summary>
        /// 项创建事件

        /// </summary>
        public event EventImageItemCreateBefore OnItemCreateBefore;


        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            if (pageSize < 1)
            {
                return;
            }

            //子控件数量不等于每页项数情况
            if (this.Controls.Count != pageSize)
            {
                this.Controls.Clear();
                AddItem();
            }
        }

        /// <summary>
        /// 按照每页显示项数添加控件
        /// </summary>
        void AddItem()
        {
            //添加显示控件
            for (int i = 0; i < pageSize; i++)
            {
                ImageDataListitem ImageDataListItem = new ImageDataListitem();
                ImageDataListItem.Name = "ImagedataListItem" + i.ToString();
                ImageDataListItem.Font = this.ItemFont;
                if (i % 2 == 0)
                ImageDataListItem.Location = new Point(0, ItemMargin + (i/2) * ((this.Height - (pageSize + 1) * ItemMargin) / pageSize *2+ ItemMargin));
                else
                    ImageDataListItem.Location = new Point((this.Width / 2) + itemMargin-2, ItemMargin + (i / 2) * ((this.Height - (pageSize + 1) * ItemMargin) / pageSize*2 + ItemMargin));
                
                ImageDataListItem.Click += new EventHandler(dataListItem_Click);
                //dataListItem.OnItemCreateBefore += new EventItemCreateBefore(dataListItem_OnItemCreateBefore);
                ImageDataListItem.BackColor = this.ItemBackColor;
                ImageDataListItem.Size = new Size((this.Width-itemMargin)/2, ((this.Height - (pageSize + 1) * ItemMargin) / pageSize*2));
                ImageDataListItem.TabIndex = i;
                Controls.Add(ImageDataListItem);
            }
        }

        /// <summary>
        /// 控件状态复位

        /// </summary>
        void ItemReset(ImageDataListitem ImageDataListItem)
        {
            ImageDataListItem.Text = "";
            ImageDataListItem.ShowImage = null;
            ImageDataListItem.dataSource = null;
            ImageDataListItem.Tag = null;
            ImageDataListItem.ItemSelectState = ButtonStateEnum.Up;
            ImageDataListItem.Font = this.ItemFont;
            ImageDataListItem.BackColor = this.itemBackColor;
            ImageDataListItem.LabelHigh = 0;
            ImageDataListItem.RightSpace = 0;
            ImageDataListItem.LeftSpace = 0;
            ImageDataListItem.Refresh();
        }

        //void dataListItem_OnItemCreateBefore(DataListItem item)
        //{
        //    if (OnItemCreateBefore != null)
        //        OnItemCreateBefore(item);
        //}

        /// <summary>
        /// 显示数据
        /// </summary>
        public void DataBind()
        {
            int start = System.Environment.TickCount;
            if (pageSize < 1)
            {
                exeTime = System.Environment.TickCount - start;
            }
            selectIndex.Clear();
            selectItemKey.Clear();

            //数据源为空

            if (DataSource != null)
                proItemMember = DataSource.GetType().GetProperty("Item");
            else
            {
                EmptyData();
                exeTime = System.Environment.TickCount - start;
                return;
            }

            //项的属性为空

            if (proItemMember == null)
            {
                EmptyData();
                exeTime = System.Environment.TickCount - start;
                return;
            }

            //获得总项数

            PropertyInfo proCountMember = DataSource.GetType().GetProperty("Count");
            if (proCountMember != null && Convert.ToInt32(proCountMember.GetValue(DataSource, null)) > 0)
            {
                dataCount = Convert.ToInt32(proCountMember.GetValue(DataSource, null));
            }
            else
            {
                EmptyData();
                exeTime = System.Environment.TickCount - start;
                return;
            }
            //键盘事件
            this.KeyUp -= new KeyEventHandler(DataListItem_KeyUp);
            this.KeyUp += new KeyEventHandler(DataListItem_KeyUp);
            //控件项数不等于每页的项数则添加

            if (this.Controls.Count != pageSize)
            {
                this.Controls.Clear();
                AddItem();
            }

            //获得数据源对象的类型
            Type type = proItemMember.GetValue(DataSource, new object[] { 0 }).GetType();

            //获得属性

            if (DisplayMember != string.Empty && DisplayMember != "")
                proTextMember = type.GetProperty(DisplayMember);
            if (KeyMember != string.Empty && KeyMember != "")
                proValueMember = type.GetProperty(KeyMember);
            if (ImageMember != string.Empty && ImageMember != "")
                proImageMember = type.GetProperty(ImageMember);
            //获取总页数

            GetPageCount();
            //显示当前页的数据
            ShowCurrPage();
            this.Focus();
            //if (IsRadio)
            //    ItemGetFocus();
            exeTime = System.Environment.TickCount - start;
        }

        /// <summary>
        /// 显示当前页数据

        /// </summary>
        /// <param name="iPageIndex"></param>
        private void ShowCurrPage()
        {
            //this.SuspendLayout();
            //当前页索引小于1
            if (pageIndex < 1)
                pageIndex = 1;
            else
                if (pageIndex > pageCount)
                    pageIndex = pageCount;
            //获得当前要显示的范围
            GetPageRange(ref rangeMin, ref rangeMax);
            object obj = null;
            ImageDataListitem idataListItem = null;
            for (int i = rangeMin; i <= rangeMax; i++)
            {
                if (i < 0 && i >= dataCount)
                    continue;
                if (i - rangeMin >= this.Controls.Count)
                    continue;
                idataListItem = (ImageDataListitem)this.Controls[i - rangeMin];
                if (idataListItem == null)
                    continue;
                idataListItem.Font = this.ItemFont;
                idataListItem.LabelHigh = this.labelHigh;
                idataListItem.RightSpace = this.rightSpace;
                idataListItem.LeftSpace = this.leftSpace;
                idataListItem.dataSource = proItemMember.GetValue(DataSource, new object[] { i });

                if (proTextMember != null)
                {
                    obj = proTextMember.GetValue(proItemMember.GetValue(DataSource, new object[] { i }), null);
                    if (obj != null)
                    {
                        if (proTextMember.PropertyType.Name == "DateTime")
                        {
                            idataListItem.Text = Convert.ToDateTime(obj).GetDateTimeFormats()[90];
                        }
                        else
                        {
                            idataListItem.Text = obj.ToString();
                        }
                    }
                }
                if (proImageMember != null)
                {
                    obj = proImageMember.GetValue(proItemMember.GetValue(DataSource, new object[] { i }), null);
                    if (obj != null)
                    {
                        if (proImageMember.PropertyType.Name == "Image")
                        {
                            idataListItem.ShowImage = (Image)obj;
                        }
                        else
                        {
                        string filename = obj.ToString();
                        ImagingFactory factory = new ImagingFactoryClass();
                        IImage img;
                        try
                        {
                            factory.CreateImageFromFile(filename, out img);
                            IBitmapImage imgB;
                            factory.CreateBitmapFromImage(img,
                                                          100,
                                                          100,
                                                          System.Drawing.Imaging.PixelFormat.Format24bppRgb,
                                                          InterpolationHint.InterpolationHintDefault,
                                                          out imgB);
                            idataListItem.ShowImage = ImageUtils.IBitmapImageToBitmap(imgB);
                        }
                        catch { idataListItem.ShowImage = null; };

                      
                         
                        }
                    }
            
                }
                if (proValueMember != null)
                {
                    obj = proValueMember.GetValue(proItemMember.GetValue(DataSource, new object[] { i }), null);
                    if (obj != null)
                    {
                        idataListItem.Tag = obj;
                    }
                }
                //单选时第一项高亮

                if (!selectIndex.Contains(i))
                {
                    if (i == rangeMin + currIndex)
                    {
                        SetItemShowState(idataListItem, ButtonStateEnum.Down);
                    }
                    else
                    {
                        SetItemShowState(idataListItem, ButtonStateEnum.Up);
                    }
                }
                else
                {
                    SetItemShowState(idataListItem, ButtonStateEnum.Down);
                }
            }
            //当本页显示的项数小于控件项数时显示空白控件

            if (rangeMax - rangeMin + 1 < pageSize)
            {
                foreach (Control ctl in this.Controls)
                {
                    if (ctl.GetType().Name == typeof(ImageDataListitem).Name)
                    {
                        idataListItem = (ImageDataListitem)ctl;
                        int ctlIndex = this.Controls.GetChildIndex((ImageDataListitem)idataListItem);
                        if (ctlIndex > rangeMax - rangeMin)
                        {
                            ItemReset(idataListItem);
                        }
                    }
                }
            }
            //this.ResumeLayout(false);
        }

        /// <summary>
        /// 向下翻页
        /// </summary>
        /// <returns>是否最后一页</returns>
        public bool NextPage()
        {
            int start = System.Environment.TickCount;
            if (pageCount <= 1)
            {
                exeTime = System.Environment.TickCount - start;
                return true;
            }
            if (pageIndex == pageCount)
            {
                exeTime = System.Environment.TickCount - start;
                return true;
            }
            else
                pageIndex = pageIndex + 1;
            ShowCurrPage();
            currIndex = 0;
            ItemGetFocus();
            exeTime = System.Environment.TickCount - start;
            if (pageIndex == pageCount)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 向上翻页
        /// </summary>
        /// <returns>是否第一页</returns>
        public bool PreviousPage()
        {
            int start = System.Environment.TickCount;
            if (pageCount <= 1)
            {
                exeTime = System.Environment.TickCount - start;
                return true;
            }
            if (pageIndex == 1)
            {
                exeTime = System.Environment.TickCount - start;
                return true;
            }
            else
                pageIndex = pageIndex - 1;
            ShowCurrPage();
            currIndex = 0;
            ItemGetFocus();
            exeTime = System.Environment.TickCount - start;
            if (pageIndex == 1)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 显示指定的页
        /// </summary>
        /// <param name="pageIndex">页码</param>
        public void ShowPage(int pageIndex)
        {
            //int start = System.Environment.TickCount;
            if (pageIndex > 0 && pageIndex <= pageCount)
            {
                this.pageIndex = pageIndex;
                ShowCurrPage();
                currIndex = 0;
                ItemGetFocus();
                //exeTime = System.Environment.TickCount - start;
                return;
            }
            //exeTime = System.Environment.TickCount - start;
        }

        /// <summary>
        /// 获得总页数

        /// </summary>
        private void GetPageCount()
        {
            if (pageSize >= this.dataCount)
            {
                pageCount = 1;
            }
            else
            {
                if (pageSize > 0)
                    if (this.dataCount % pageSize == 0)
                    {
                        pageCount = this.dataCount / pageSize;
                    }
                    else
                    {
                        pageCount = this.dataCount / pageSize + 1;
                    }
            }
        }


        /// <summary>
        /// 获得当前页的元素范围
        /// </summary>
        /// <param name="iMin"></param>
        /// <param name="iMax"></param>
        private void GetPageRange(ref int iMin, ref int iMax)
        {
            //如果只有一页

            if (pageCount == 1)
            {
                iMin = 0;
                iMax = dataCount - 1;
            }
            //如果不是最后一页或者最后余数为0
            else if (pageIndex != pageCount || this.dataCount % pageSize == 0)
            {
                iMin = (pageIndex - 1) * pageSize;
                iMax = iMin + pageSize - 1;
            }
            //是最后一页而且余数不为0
            else
            {
                iMin = this.dataCount - this.dataCount % pageSize;
                iMax = this.dataCount - 1;
            }
        }

        void DataListItem_KeyUp(object sender, KeyEventArgs e)
        {
            if (isRadio)
            {
                if (e.KeyCode == Keys.Up)
                {
                    if (currIndex == 0)
                        currIndex = rangeMax - rangeMin;
                    else
                        currIndex = currIndex - 1;
                    ItemGetFocus();
                }
                if (e.KeyCode == Keys.Down)
                {
                    if (currIndex == rangeMax - rangeMin)
                        currIndex = 0;
                    else
                        currIndex = currIndex + 1;
                    ItemGetFocus();
                }
                if (e.KeyCode == Keys.Enter)
                {
                    if (OnItemClick != null)
                        OnItemClick((ImageDataListitem)this.Controls[currIndex]);
                }
            }
        }

        private void ItemGetFocus()
        {
            if (isRadio)
            {
                ImageDataListitem dataListItem = new ImageDataListitem ();
                foreach (Control ctl in this.Controls)
                {
                    if (ctl.GetType().Name == typeof(ImageDataListitem).Name)
                    {
                        dataListItem = (ImageDataListitem)ctl;
                        if (dataListItem.TabIndex > rangeMax - rangeMin)
                            break;
                        if (dataListItem.TabIndex == currIndex)
                        {
                            if (dataListItem.ItemSelectState == ButtonStateEnum.Up)
                            {
                                SetItemShowState(dataListItem, ButtonStateEnum.Down);
                                OpSelectItemList(dataListItem.Tag, true);
                            }
                        }
                        else
                        {
                            if (dataListItem.ItemSelectState == ButtonStateEnum.Down)
                            {
                                SetItemShowState(dataListItem, ButtonStateEnum.Up);
                                OpSelectItemList(dataListItem.Tag, false);
                            }
                        }
                    }
                }
            }
        }

        private void EmptyData()
        {
            if (this.Controls.Count != pageSize)
            {
                this.Controls.Clear();
                AddItem();
            }
            else
            {
                ImageDataListitem dataListItem;
                foreach (Control ctl in this.Controls)
                {
                    if (ctl.GetType().Name == typeof(ImageDataListitem).Name)
                    {
                        dataListItem = (ImageDataListitem)ctl;
                        ItemReset(dataListItem);
                    }
                }
            }
        }

        void dataListItem_Click(object sender, EventArgs e)
        {
            this.Focus();
            if (DataSource == null || proItemMember == null || dataCount == 0)
                return;
            if (((Control)sender).TabIndex > rangeMax - rangeMin)
                return;
            {

                ImageDataListitem dataListItem = new ImageDataListitem();
                foreach (Control ctl in this.Controls)
                {
                    if (ctl.GetType().Name == typeof(ImageDataListitem).Name)
                    {
                        dataListItem = (ImageDataListitem)ctl;
                        if (dataListItem.TabIndex > rangeMax - rangeMin)
                            break;
                        if (dataListItem.TabIndex == ((ImageDataListitem)sender).TabIndex)
                        {
                            if (dataListItem.ItemSelectState == ButtonStateEnum.Up)
                            {
                                SetItemShowState(dataListItem, ButtonStateEnum.Down);
                                currIndex = dataListItem.TabIndex;
                                OpSelectItemList(dataListItem.Tag, true);
                            }
                        }
                        else
                        {
                            if (dataListItem.ItemSelectState == ButtonStateEnum.Down)
                            {
                                SetItemShowState(dataListItem, ButtonStateEnum.Up);
                                OpSelectItemList(dataListItem.Tag, false);
                            }
                        }
                    }
                }
                if (OnItemClick != null)
                    OnItemClick((ImageDataListitem)sender);
            }


        }

        void SetItemShowState(ImageDataListitem idataListItem, ButtonStateEnum itemState)
        {
            if (itemState == ButtonStateEnum.Up)
            {
                idataListItem.ForeColor = this.itemForeColor;
                idataListItem.BackColor = this.itemBackColor;
                idataListItem.Font = this.ItemFont;
                idataListItem.ItemSelectState = ButtonStateEnum.Up;
                OpSelectItemList(idataListItem.Tag, false);
            }
            else
            {
                idataListItem.ForeColor = this.selectItemForeColor;
                idataListItem.BackColor = this.selectItemBackColor;
                idataListItem.Font = this.SelectItemFont;
                idataListItem.ItemSelectState = ButtonStateEnum.Down;
                OpSelectItemList(idataListItem.Tag, true);
            }
            if (OnItemCreateBefore != null)
                OnItemCreateBefore(idataListItem);
            //何时刷新整个控件
            //1.更改了图标框的长度时
            //2.项的图标列表为空，适用于最后一页有空项的情况，从显示数据刷为空项

            //3.当有图标列表但是图标显示状态为假的时候，适用于更改图标索引，更改图标索引时图标显示状态置为假
            //    if (dataListItem.IconWidth != this.iconWidth || dataListItem.ItemsIconList == null || (dataListItem.ItemsIconList != null && !dataListItem.exitsIcon))
                  idataListItem.Refresh();
            //    else
            {
              //      idataListItem.Invalidate(new Rectangle(0, idataListItem.Top, this.Width, idataListItem.Height));
            //    idataListItem.Update();
            }
        }



        void OpSelectItemList(object tag, bool isAdd)
        {
            if (tag != null)
            {
                string key = tag.ToString();
                if (selectItemKey.Contains(key) && !isAdd)
                {
                    selectItemKey.Remove(key);
                }
                if ((!selectItemKey.Contains(key)) && isAdd)
                {
                    if (isRadio)
                        selectItemKey.Clear();
                    selectItemKey.Add(key);
                }
            }
        }

        /// <summary>
        /// 更改指定项的图标索引
        /// </summary>
        /// <param name="ItemIndex">项的索引</param>
        /// <param name="IconIndex">图标索引</param>
        /// <returns>是否成功</returns>
    }
    public delegate void EventImageItemClick(ImageDataListitem item);
    public delegate void EventImageItemCreateBefore(ImageDataListitem item);
    }
